# 2.10 练习题-全局⽂本检索替换
# 写⼀个脚本，允许⽤户按以下⽅式执⾏时，即可以对指定⽂件内容进⾏全局替换，且替换完毕后打印替
# 换了多少处内容
# 写完后的脚本调⽤⽅式：
# python your_script.py old_str new_str filename

import re
import sys, os

def str_replace(old, new, filename):
    num = 0
    new_file = 'newFile'
    newfp = open(new_file, 'w', encoding='utf-8')
    with open(filename, 'r', encoding='utf-8') as fp:
        for line in fp:
            if old not in line:
                newfp.write(line)
                continue
            # num += len(re.findall())
            line, n = re.subn(old, new, line)
            num += n
            newfp.write(line)
    newfp.close()
    os.remove(filename)
    os.rename(new_file, filename)
    return num

if __name__ == '__main__':
    print('共替换了',str_replace(sys.argv[1], sys.argv[2], sys.argv[3]),'处内容')
